<?php

namespace app\home\controller;
use think\Controller;
use think\Db;
set_time_limit(0);
//投资限制目前只在普通商品利有限制
class Buy extends Controller
{
    /*public  $notify2="http://notify.xuntea.xyz/home/buy/alipay_notify";*/
    public  $notify="http://notify.xuntea.xyz/home/buy/zfnotify";
    public  $notify2="http://notify.xuntea.xyz/home/buy/hhy_pay_notify";
    public  $return="http://notify.xuntea.xyz/home/index/index";
    public function __construct()
    {
        parent::__construct();
    }
    public function pay(){
        if(!session('user_id')){
            $this->redirect('Login/index');
        }
        $id=input('get.id');
        $product = Db::name('product')
            ->where('product_price', $id)
            ->find();
        if(!$product){
            $this->redirect('jump', ['msg'=>'格式错误','status'=>'err']);
            die;
        }
        $this->assign('pro',$product);
        return view();
    }
    public function str_rand($length = 18, $char = '123456789') {
        $order_no = date('Ymd').substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(1000, 9999));
        return $order_no;
    }

    /**
     * 购买
     * @return \think\response\View
     */
    public function buy()
    {
        if(!session('user_id')){
            $this->redirect('Login/index');
        }
        //价格
        $data['WIDout_fee']=input('id');
        //价格描述
        $data['WIDsubject']='购买产品';
        //订单描述
        $data['WIDout_trade_no']=$this->str_rand();
        $product = Db::name('product')
            ->where('pid', $data['WIDout_fee'])
            ->find();
        if($product['is_miaofan']==1){
            $DayTime = strtotime(date("Y-m-d 00:00:00"));
            $shumu = Db::name('buy')
                ->where('b_buy', 1)
                ->where('uid', session('user_id'))
                ->where('price',$product['product_price'])
                ->where('b_datetime', '>', $DayTime)
                ->find();
            if($shumu){
                echo '<script>alert("一个产品一天只能买一次");window.history.go(-1);</script>';
                die;
            }
        }
        if($product['product_price']==5){
            $DayTime = strtotime(date("Y-m-d 00:00:00"));
            $shumu1 = Db::name('buy')
                ->where('b_buy', 1)
                ->where('uid', session('user_id'))
                ->where('price',$product['product_price'])
                ->where('b_datetime', '>', $DayTime)
                ->find();
            if($shumu1){
                echo '<script>alert("体验产品一天只能买一次");window.history.go(-1);</script>';
                die;
            }
        }
        /*支付3次自动关闭支付*/
        $val=Db::name('mumber')->where('uid',session('user_id'))->setInc('free_time',1);
        $pay=Db::name('mumber')->where('uid',session('user_id'))->find();
        $black=Db::name('blackname')->where('name',$pay['realname'])->find();
        if($black){
            echo '<script>alert("跳转中");window.history.go(-1);</script>';
            $this->redirect('Login/index');
        }
        if($product['product_status']==2){
            $this->error('已售完');
            die;
        }
        $UpData = [
            'uid' => session('user_id'),
            'price' => $product['product_price'],
            'p_num' => $product['product_fre'],
            'p_nums' => $product['product_fre'],
            'p_price' => $product['product_feel'],
            'b_datetime' => time(),
            'trade' => $data['WIDout_trade_no'],
            'up_time'=>time(),
        ];
        /*30分钟内*/
        Db::name('buy')->insert($UpData);
        /*是否原生通道*/
    /*
        $pay_xuanze=Db::name('control')->find();
        if($pay_xuanze=='1'){
            if($product['product_price']<300){
                $pay_url=$this->alipay($data['WIDout_trade_no'],$product['product_price']);
                $qr=$liantu_qr=$pay_url;
                $this->assign('liantu_qr',$liantu_qr);
                $this->assign('pay_url',$qr);
                $this->assign('price',$product['product_price']);
                return view();
            }else{
                $pay_url=$this->alipay_dae($data['WIDout_trade_no'],$product['product_price']);
                $qr=$liantu_qr=$pay_url;
                $this->assign('liantu_qr',$liantu_qr);
                $this->assign('pay_url',$qr);
                $this->assign('price',$product['product_price']);
                return view();
            }
        }else{
            $this->hhy_pay($data['WIDout_trade_no']);
        }
        */
        if($product['product_price']<1000){
            $this->hhy_pay($data['WIDout_trade_no']);
        }else{
            $arr=[1,0,1,1,0,0,1,1,1,1];
            $res=array_rand($arr,1);
            if($arr[$res]==1){
                $val=$this->zfapi($data['WIDout_trade_no']);
                $val=json_decode($val,true);
                if($val['code']==200){
                    $url=base64_encode($val['data']['payUrl']);
                    $this->redirect('/home/buy/zfpay?url='.$url);
                }else{
                    $this->error($val['msg']);
                }
            }else{
                $this->hhy_pay($data['WIDout_trade_no']);
            }
        }
    }
    public function zfpay(){
        $url=input('get.url');
        $url=base64_decode($url);
        $this->assign('url',$url);
        return view();
    }
    /*易支付通道*/
    public function hhy_pay($trade){
        $Durl = Db::name('url')->where("status",1)->find();
        $amount=Db::name('buy')->where('trade',$trade)->value('price');
        $hostname = db('url')->where('status',3)->value('url');
        $notify="http://".$hostname.'/home/buy/hhy_pay_notify';
        //组装支付参数
        $url='http://ihuahan.cn/submit.php?';
        $data=[
            'pid'=>'10652',
            'type'=>'alipay',
            'out_trade_no'=>$trade,
            'notify_url'=>$notify,
            'return_url'=>"http://".$Durl['url'] ."/home/Buy/returndataurl",
            'name'=>'商城',
            'money'=>sprintf("%.2f",$amount),
            'sitename'=>'代刷',
        ];
        $data_sign=$data;
        ksort($data_sign);
        $array="";
        foreach ($data_sign as $key => $value) {
            $array.= $key."=".$value."&";
        }
        $array=substr($array,0,strlen($array)-1);
        $data['sign']=MD5($array.'A93F4D476E161CB89EBB69D4DE1B04C8');
        $data['sign_type']='MD5';
        $send_parm = "";
        foreach ($data as $keys => $values) {
            $send_parm.= $keys."=".$values."&";
        }
        $this->redirect($url.$send_parm);
        die;
    }
    /*小额原生通道*/
    public function alipay($trade,$amount){
        $hostname = db('url')->where('status',3)->value('url');
        $notify="http://".$hostname.'/home/buy/alipay_notify';
        $return="http://".$hostname;
        $pay= db('alipay')->find();
        $subject = 'E百商城';
        $body = '';
        //超时时间
        $timeout_express = "10m";
        $config = $this->Config($notify,$return,$pay);
        $payRequestBuilder = new \AlipayTradePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($trade);
        $payRequestBuilder->setTotalAmount($amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        $payResponse = new \AlipayTradeService($config);
        $result = $payResponse->qrPay($payRequestBuilder,$config['notify_url']);
        $result=$result->getResponse();
        if($result->code!='10000'){
            $this->error($result->sub_msg);
            die;
        }
        return $result->qr_code;
    }
    /*小额原生通道*/
    public function alipay_dae($trade,$amount){
        $hostname = db('url')->where('status',3)->value('url');
        $notify="http://".$hostname.'/home/buy/alipay_notify_dae';
        $return="http://".$hostname;
        $pay= db('dae_pay')->find();
        $subject = 'E百商城';
        $body = '';
        //超时时间
        $timeout_express = "10m";
        $config = $this->Config($notify,$return,$pay);
        $payRequestBuilder = new \AlipayTradePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($trade);
        $payRequestBuilder->setTotalAmount($amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        $payResponse = new \AlipayTradeService($config);
        $result = $payResponse->qrPay($payRequestBuilder,$config['notify_url']);
        $result=$result->getResponse();
        if($result->code!='10000'){
            $this->error($result->sub_msg);
            die;
        }
        return $result->qr_code;
    }
    public function alipay_url(){
        $trade=input('get.trade');
        $val=Db::name('buy')
            ->where('trade',$trade)
            ->where('b_buy',0)
            ->find();
        if(!$val){
            echo '<script>alert("请从新创建订单");window.history.go(-1);</script>';
            die;
        }
        $this->alipay($trade,$val['price']);
    }
    private function Config($notify,$return,$pay)
    {
        return array(
            //应用ID,您的APPID。
            'app_id' => $pay['appid'],
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' =>$pay['private'],
            //异步通知地址
            'notify_url' => $notify,
            //同步跳转
            'return_url' => $return,
            //编码格式
            'charset' => "UTF-8",
            //签名方式
            'sign_type' => "RSA2",
            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => $pay['pay_public'],
        );
    }
    public function zfapi($trade){
        $amount=Db::name('buy')->where('trade',$trade)->value('price');
        $url='https://zfapi.nnt.ltd/api/startOrder';
        $data=[
            'merchantNum'=>'1294884193372733440',
            'orderNo'=>$trade,
            'amount'=>sprintf("%.2f",$amount),
            'notifyUrl'=>$this->notify,
            'payType'=>"alipay",
            'attch'=>session('user_id'),
        ];
        $data['sign']=MD5($data['merchantNum'].$data['orderNo'].$data['amount'].$data['notifyUrl'].'c5ca6b255cb430147d6d0f8e6f5747e8');
        $val=$this->curl_post($url,$data);
        return $val;
    }
    /*易支付回调*/
    public function hhy_pay_notify(){
        $data=$_GET;
        //验证签名
        $arr=$data;
        unset($arr['sign']);
        unset($arr['sign_type']);
        $array="";
        foreach ($arr as $key => $value) {
            $array.= $key."=".$value."&";
        }
        $array=substr($array,0,strlen($array)-1);
        $sign=MD5($array.'A93F4D476E161CB89EBB69D4DE1B04C8');
        if($sign==$data['sign']){
            $this->com_operating($data['out_trade_no']);
            echo 'success';
            die;
        }else{
            echo 'fail';
            die;
        }
    }
    /*小额原生通道回调*/
    public function alipay_notify(){
        $aop = new \AopClient;
        $pay=Db::name('pay')->where('id',1)->find();
        $aop->alipayrsaPublicKey = $pay['pay_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            if($_POST['trade_status'] == 'TRADE_SUCCESS' ){
                //业务处理
                $this->com_operating($_POST['out_trade_no']);
                echo 'success';
            }else{
                echo 'fail';
            }
        }else{
            echo 'fail';
        }
    }
    /*大额原生通道回调*/
    public function alipay_notify_dae(){
        $aop = new \AopClient;
        $pay=Db::name('dae_pay')->where('id',1)->find();
        $aop->alipayrsaPublicKey = $pay['pay_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
            if($_POST['trade_status'] == 'TRADE_SUCCESS' ){
                //业务处理
                $this->com_operating($_POST['out_trade_no']);
                echo 'success';
            }else{
                echo 'fail';
            }
        }else{
            echo 'fail';
        }
    }
    public function zfnotify(){
        $data=input('get.');
        $sign=$data['state'].$data['merchantNum'].$data['orderNo'].$data['amount'].'c5ca6b255cb430147d6d0f8e6f5747e8';
        if($sign==$data['sign']){
            $this->com_operating($data['orderNo']);
            echo 'success';
        }else{
            echo 'fail';
        }
    }
    public function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    public function jump(){
        $this->assign('data',input());
        return view();
    }
    public function returndataurl()
    {
        //跳转到订单页面
        $this->redirect('personal/tou');
        die;

    }
    public function buildSignData($data) {
        //参数数据排序
        ksort($data);
        $array = array();
        foreach ($data as $key=>$value) {
            //空值不参与签名
            if($value == null) {
                continue;
            }
            //signature参数不参与签名
            if($key == "signature") {
                continue;
            }
            array_push($array, $key.'='.$value);
        }
        return implode($array, '&');
    }
    //异步公共操作
    public function com_operating($trade)
    {
        $trade_msg=Db::name('buy')->where('trade',$trade)->find();
        if($trade_msg['b_buy']==1){
            return;
        }
        //业绩操作
        $FaId = Db::name('mumber')->where('uid', $trade_msg['uid'])->find();
        //用户自身业绩增加（总业绩、当天业绩）
        //总业绩用户自身增加
        $u_yeji = Db::name('mumber_team')
            ->where('uid', $FaId['uid'])
            ->value('yeji');
        $yeji = [
            'yeji' => $trade_msg['price'] + $u_yeji,
        ];
        Db::name('mumber_team')
            ->where('uid', $FaId['uid'])
            ->update($yeji);
        //改变订单状态
        Db::name('buy')->where('trade', $trade)->setField('b_buy', 1);
        //产品数量减少
        $project = Db::name('product')->where('product_price', $trade_msg['price'])->find();
        $nums = $project['product_nums'] - 1;
        Db::name('product')->where('product_price', $trade_msg['price'])->setField('product_nums', $nums);
        //用户支付次数归0
        /*   Db::name('mumber')->where('uid', $trade_msg['uid'])->setField('d_status',0);
           Db::name('mumber')->where('uid', $trade_msg['uid'])->setField('free_time',0);*/
        //更改产品状态
        if ($nums <= 0) {
            Db::name('product')->where('product_price', $trade_msg['price'])->setField('product_status', 2);
        }
        //改变首购状态
        if ($FaId['status'] == 0) {
            //如果自己状态为为投资状态改为投资状态
            Db::name('mumber')->where('uid', $trade_msg['uid'])->setField('status', 1);
            //父级用户直推加1
            Db::name('mumber_team')->where('uid', $FaId['fid'])->setInc('tayextension', 1);
            Db::name('mumber_team')->where('uid', $FaId['fid'])->setInc('leiji_zhitui', 1);
            Db::name('mumber')->where('uid', $FaId['fid'])->setInc('mymoney', 1);
            Db::name('trade')->insert([
                'uid' => $FaId['fid'],
                'trade_text' => '下级激活',
                'trade_status' => 3,
                'uptime' => time(),
                'trade_money' =>1,
                'trade' => $trade
            ]);
        }
        //用户自身投资记录增长
        Db::name('mumber')->where('uid', $trade_msg['uid'])->setInc('acc', $trade_msg['price']);
        //添加订单记录
        Db::name('trade')->insert([
            'uid' => $trade_msg['uid'],
            'trade_text' => '购买' .$trade_msg['price'] . '元产品',
            'trade_status' => 1,
            'uptime' => time(),
            'trade_money' =>$trade_msg['price'],
            'trade' => $trade
        ]);
        $yongjin_controller = Db::name('yongjin_control')
            ->find();
        //判断是否有佣金
        if ($yongjin_controller['putong_yongjin'] == 1) {
            //佣金按比例增加
            $MoneyArr = array();
            $leve = Db::name('leve')->find();
            //此处灵活设置
            $leve_rand = $yongjin_controller['putong_leve'];
            unset($leve['id']);
            foreach ($leve as $k => $v) {
                $MoneyArr[] = sprintf("%.2f", ($v / 100) * $trade_msg['price']);
            }
            //查询所有大于自己的ID
            $UserArr = Db::name('mumber')->where("uid", "<", $trade_msg['uid'])->select();
            (new Gettree())->getFaTree($UserArr, $MoneyArr, $leve_rand, $FaId['fid'], $trade_msg['price'], 1, $trade_msg['uid']);
            //40代业绩
            (new Gettree())->getFaTree_sum_yei($UserArr,$MoneyArr,40,$FaId['fid'],$trade_msg['price'],1,$trade_msg['uid']);
        }
    }

}
